<?php
namespace Utuo;

class Score {
	
	public static $errorsInfo = array(
		'r0' => '执行成功',
		'r1' => '抱歉当前操作不能积分',
		'r2' => '操作次数超出限制',
	);
	
	
	/**
	 * 执行积分处理
	 * @param string $tag
	 */
	public static function exec($sid, $tag = "", $resultConfig = null ) {
		$sessionUser = session('user');
		$uid = $sessionUser['id'];
		if ( !empty($resultConfig) ) {
			Score::$errorsInfo = array_merge(Score::$errorsInfo, $resultConfig);
		}
		function result($errorCode) {
			return array(
				'error' => $errorCode,
				'msg' => \Utuo\Score::$errorsInfo[$errorCode],
			);
		}
		$scorePoint = M("ScorePoint a")->join("__SCORE_EVENT__ b on a.event_id=b.id")->where("a.cid=%d and b.tag='{$tag}' and b.status=1 and b.is_deleted=0 and a.status=1 and a.is_deleted=0", $sid)->field("a.*")->find();
		if( $scorePoint and ($scorePoint['score'] or $scorePoint['experience'])) {
			// 验证行为可否执行
			if ( (int)$scorePoint['times'] != -1 ) {
				$scoreRecordCount = M("ScoreRecord")->where('event_id=%d and uid=%d', $scorePoint['event_id'], $uid)->count();
				if ( $scoreRecordCount >= (int)$scorePoint['times'] ) {
					return result( 'r2' );
				}
			}		
			// 更新总积分
			$score = M("Score")->where('cid=%d and uid=%d', $sid, $uid)->find();
			$score or ($score = array(
						'uid' => $uid,
						'cid' => $sid,
						'total_score' => 0,
						'total_consume' => 0,
						'total_expirese' => 0,
					  ) and $score['id'] = M("Score")->add($score));
			$score[$scorePoint['score'] > 0 ? 'total_score' : 'total_consume'] += $scorePoint['score']; // 积分变动
			$score['total_expirese'] += $scorePoint['experience'];  // 经验变动
			M("Score")->save($score);
			// 积分记录
			$scoreRecord = array('uid' => $uid,
								 'cid' => $sid,
								 'event_id' => $scorePoint['event_id'],
								 'score' => $scorePoint['score'],
								 'experience' => $scorePoint['experience'],);
			M("ScoreRecord")->add($scoreRecord);
			return result( 'r0' );
		} else {
			return result( 'r1' );
		}
	}
	
}


